<script setup lang="ts">
  import { ref, toRefs, nextTick, PropType, computed } from 'vue'
  import ReservationTime from '../../dialog/reservation-time/ReservationTime.vue'
  import { ArrowDown } from '@element-plus/icons-vue'
  import WaitHandle from './wait-handle/WaitHandle.vue'
  import UpdateNetwork from '@/components/pages/order/list/update-network/UpdateNetwork.vue'
  import AssignNetwork from '@/components/pages/order/list/assign-network/AssignNetwork.vue'
  import AssignCustomerService from '@/components/pages/order/list/assign-customer-service/AssignCustomerService.vue'
  import UpdateCustomerService from '../../dialog/update-customer-service/UpdateCustomerService.vue'
  import FinishOrder from '@/components/pages/order/list/finish-order/FinishOrder.vue'
  import CancelOrder from '@/components/pages/order/list/cancel-order/CancelOrder.vue'
  import Reminder from '@/components/pages/order/list/reminder/Reminder.vue'
  import UpdateOrderInfoModal from '@/components/pages/order/detail/pages/body/order-info/UpdateOrderInfoModal.vue'
  import { useGetOrderWaitHandleList } from '@/services/pages/order/useOrderDetail'
  import CheckEndOrderModal from './check-setttlement-order/CheckStatementOrder.vue'
  import CheckQuote from './check-quote/Index.vue'
  import CheckCode from './check-code/index.vue'
  import fixedData from '@/config/fixed-data/order/order'
  import OrderPrint from './order-print/OrderPrint.vue'
  import '@/utils/Print'
  import { getOrderFeeDetailPrint } from '@/api/order'
  import { useUserStore } from '@/store/modules/user'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { ElMessageBox } from 'element-plus'
  import { useCheckInvoiceByIds } from '@/services/pages/order/useOrder'
  import AssignEngineerModal from './assign-engineer-modal.vue'
  import CheckFeeDrawer from './check-fee-modal/Index.vue'

  const {
    list: orderWaitHandleList,
    getListLoading: getOrderWaitHandleListLoading,
    getList: getOrderWaitHandleList,
  } = useGetOrderWaitHandleList()
  const { check: checkAppliedInvoiceByOrderIds } = useCheckInvoiceByIds()

  defineOptions({
    name: 'OrderDetailHeaderBtnGroup',
  })

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
    checkQuoteBtnVisible: {
      type: Boolean,
      default: () => false,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
    (e: 'updateCostList'): void
    (e: 'updatePartList'): void
    (e: 'update-list'): void
    (e: 'end-order-finish'): void
    (e: 'check-quote-finish'): void
  }>()

  // 工单打印组件实例
  const orderPrintInstance = ref<InstanceType<typeof OrderPrint> | null>(null)
  const assignEngineerModalVisible = ref(false)

  /**
   * 是否填写了故障库
   */
  const isFillFault = computed(() => {
    if (userStore.$state.role[0] && userStore.$state.role[0].roleType === 1) {
      return true
    }

    if (props.orderDetail.moduleId === fixedData.buy_spare_part) {
      return true
    }

    if (!props.orderDetail.fault || props.orderDetail.faultReason.length === 0) {
      return false
    }

    return true
  })

  // 客户状态管理
  const userStore = useUserStore()

  // 审核接单信息弹窗显示状态
  const checkEndOrderModalVisible = ref(false)

  // 审核报价弹窗显示状态
  const checkQuoteModalVisible = ref(false)

  const { orderDetail } = toRefs(props)
  const assignCustomerServiceDialogVisible = ref(false)
  const updateCustomerServiceDialogVisible = ref(false)
  const finishOrderDialogVisible = ref(false)
  const cancelDialogVisible = ref(false)
  const reminderDialogVisible = ref(false)
  const reservationTimeDialogVisible = ref(false)
  const updateOrderInfoModalVisible = ref(false)
  const printInfo = ref({})
  // 打印b，催单a
  const handleCommand = (command: string | number | object) => {
    if (command == 'b') {
      // ElMessage({
      //   message: '正在升级维护中，敬请期待...',
      //   type: 'success',
      //   duration: 5000,
      //   showClose: true,
      //   plain: true,
      // })
    }
  }

  const onPrintClick = () => {
    getOrderFeeDetailPrint(orderDetail.value.id).then((res) => {
      const row = res.data.data.row
      printInfo.value = row
      nextTick(() => {
        let title = ''
        Print('#printId', {
          onStart: function () {
            title = window.document.title
            window.document.title = row.workNo + '-' + row.repairCompanyUser
          },
          onEnd: function () {
            window.document.title = title
          },
        })
      })
    })
  }

  // 待处理组件实例
  const waitHandleEventRef = ref<InstanceType<typeof WaitHandle> | null>(null)

  /**
   * 公司地址
   * 用于传递给分派部门弹窗组件
   */
  const userAddress = ref({
    province: '',
    city: '',
    area: '',
    town: '',
    address: '',
  })

  /**
   * 是否显示审核序列号按钮
   */
  const isShowCheckCodeBtn = computed(() => {
    return orderWaitHandleList.value.map((item) => item.type).includes(7)
  })

  /**
   * 获取待处理事项方法
   */
  const getWaitHandleEventList = () => {
    if (waitHandleEventRef.value) {
      waitHandleEventRef.value.getData()
    }
  }

  const assignNetworkDialogVisible = ref(false)
  const onAssignNetworkBtnClick = () => {
    if (orderDetail.value) {
      setUserAddress()
      assignNetworkDialogVisible.value = true
    }
  }

  const updateNetworkDialogVisible = ref(false)
  const onUpdateNetworkBtnClick = () => {
    if (orderDetail.value) {
      setUserAddress()
      updateNetworkDialogVisible.value = true
    }
  }

  const setUserAddress = () => {
    if (orderDetail.value) {
      Object.assign(userAddress.value, {
        province: orderDetail.value.province,
        city: orderDetail.value.city,
        area: orderDetail.value.area,
        town: orderDetail.value.town,
        address: orderDetail.value.address,
      })
    }
  }

  /**
   * 审核序列号更新事件
   */
  const onCheckCodeUpdate = () => {
    emits('update')
    getOrderWaitHandleList(props.orderDetail.id)
  }

  /**
   * 确认开票点击事件
   */
  const onConfirmOpenTicket = () => {
    ElMessageBox({
      title: '提示',
      message: '是否确认开票？',
      showCancelButton: true,
      autofocus: false,
      cancelButtonText: '否',
      confirmButtonText: '是',
      type: 'warning',
      beforeClose(action, instance, done) {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          checkAppliedInvoiceByOrderIds([props.orderDetail.id])
            .then((res) => {
              if (res.code === 20000) {
                done()
                HMessage.success('确认成功')
                emits('update')
              } else {
                HMessageBox.error(res.message)
              }
            })
            .finally(() => {
              instance.cancelButtonLoading = false
              instance.confirmButtonLoading = false
            })
          return
        }

        done()
      },
    })
  }

  const onAssignEngineerClick = () => {
    assignEngineerModalVisible.value = true
  }

  defineExpose({
    getWaitHandleEventList,
    getOrderWaitHandleList,
  })
</script>

<template>
  <div>
    <div class="order_detail_header_btns">
      <h-plain-button
        v-if="props.orderDetail.invoice === false && props.orderDetail.openTicket"
        v-permission="'order_sureOpenTicket'"
        @click="onConfirmOpenTicket"
      >
        确认开票
      </h-plain-button>
      <check-code
        v-if="isShowCheckCodeBtn && props.orderDetail.status === 3 && isFillFault"
        :order-id="props.orderDetail.id"
        @update="onCheckCodeUpdate"
      />
      <h-plain-button
        v-if="
          orderWaitHandleList.filter((item) => item.type === 3).length &&
          props.orderDetail.status === 3 &&
          isFillFault
        "
        v-permission="'order_end'"
        @click="checkEndOrderModalVisible = true"
      >
        审核结单信息
      </h-plain-button>
      <check-fee-drawer
        v-if="orderWaitHandleList.filter((item) => item.type === 1).length"
        :work-id="orderDetail.id"
        :work-no="orderDetail.orderNo"
        @update="emits('updateCostList')"
      >
        <h-plain-button v-permission="'order_review_fee'" :loading="getOrderWaitHandleListLoading">
          审核费用信息
        </h-plain-button>
      </check-fee-drawer>
      <!-- <check-fee-drawer
        v-if="orderWaitHandleList.filter((item) => item.type === 1).length"
        :work-id="orderDetail.id"
        :work-no="orderDetail.orderNo"
        @update="() => emits('updateCostList')"
      >
        <h-plain-button :loading="getOrderWaitHandleListLoading">审核费用信息</h-plain-button>
      </check-fee-drawer> -->
      <!-- <wait-handle
        v-if="![4, 5].includes(orderDetail.status)"
        ref="waitHandleEventRef"
        :order-id="orderDetail.id"
        :order-no="orderDetail.orderNo"
        :network="orderDetail.network || ''"
        :network-id="orderDetail.networkId"
        :emp="orderDetail.emp"
        @update="() => emits('update')"
        @update-cost-list="() => emits('updateCostList')"
        @update-part-list="() => emits('updatePartList')"
      /> -->
      <h-plain-button
        v-if="[1, 2, 3].includes(orderDetail.status)"
        v-permission="'order_update'"
        @click="updateOrderInfoModalVisible = true"
      >
        处理工单
      </h-plain-button>
      <!-- <HPlainButton
        v-if="!orderDetail.assignEmp && orderDetail.status !== 4"
        @click="assignCustomerServiceDialogVisible = true"
        >分派客服
      </HPlainButton>
      <HPlainButton
        v-else-if="
          orderDetail.assignEmp &&
          (orderDetail.status === 1 || orderDetail.status === 2 || orderDetail.status === 3)
        "
        @click="updateCustomerServiceDialogVisible = true"
        >改派客服</HPlainButton
      > -->
      <h-plain-button
        v-if="orderDetail.status === 1"
        v-permission="'order_assignNetwork'"
        @click="onAssignNetworkBtnClick"
      >
        分派部门
      </h-plain-button>
      <h-plain-button
        v-else-if="orderDetail.status != 4"
        v-permission="'order_updateNetwork'"
        @click="onUpdateNetworkBtnClick"
      >
        改派部门
      </h-plain-button>
      <template v-if="orderDetail.status === 3 && orderDetail.dispatchNetwork === 2">
        <h-plain-button
          v-if="
            props.orderDetail.network &&
            props.orderDetail.engineerManagerEmp &&
            props.orderDetail.status === 3
          "
          v-permission="'order_dispatch_engineer'"
          @click="onAssignEngineerClick"
        >
          改派工程师
        </h-plain-button>
        <h-plain-button
          v-if="props.orderDetail.network && !props.orderDetail.engineerManagerEmp"
          v-permission="'order_dispatch_engineer'"
          @click="onAssignEngineerClick"
        >
          分派工程师
        </h-plain-button>
      </template>
      <!-- <HPlainButton v-if="orderDetail.status === 3" @click="reservationTimeDialogVisible = true"
        >预约</HPlainButton
      > -->
      <h-plain-button v-permission="'order_print'" @click="onPrintClick">打印</h-plain-button>
      <h-plain-button v-if="false">结单</h-plain-button>
      <el-dropdown trigger="click" @command="handleCommand">
        <h-button>
          <span>更多</span>
          <el-icon style="margin-left: 5px">
            <ArrowDown />
          </el-icon>
        </h-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-if="!(orderDetail.status === 4 || orderDetail.status === 5)"
              command="reminder"
              @click="reminderDialogVisible = true"
            >
              催单
            </el-dropdown-item>
            <div v-permission="'order_updateFinisher'">
              <el-dropdown-item
                v-if="!(orderDetail.status === 4 || orderDetail.status === 5)"
                command="finish"
                @click="finishOrderDialogVisible = true"
              >
                完成
              </el-dropdown-item>
            </div>
            <div v-permission="'order_cancel'">
              <el-dropdown-item
                v-if="!(orderDetail.status === 4 || orderDetail.status === 5)"
                command="cancel"
                @click="cancelDialogVisible = true"
              >
                取消
              </el-dropdown-item>
            </div>
            <!-- <div>
              <el-dropdown-item command="b">打印</el-dropdown-item>
            </div> -->

            <!-- <template v-if="props.orderDetail && ![4, 5].includes(orderDetail.status)">
              <service-process :work-id="orderDetail.id">
                <el-dropdown-item command="c">服务过程</el-dropdown-item>
              </service-process>
            </template> -->
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <assign-network
      v-model="assignNetworkDialogVisible"
      :is-batch="false"
      :network-id="orderDetail.networkId"
      :network="orderDetail.network"
      :selecttion="[orderDetail.id]"
      :address="userAddress"
      @update="emits('update')"
    />

    <assign-customer-service
      v-model="assignCustomerServiceDialogVisible"
      :is-batch="false"
      :order-ids="[orderDetail.id]"
      :current-emp="orderDetail.emp"
      @update="emits('update')"
    />

    <update-customer-service
      v-model="updateCustomerServiceDialogVisible"
      :order-id="orderDetail.id"
      :current-emp="orderDetail.emp || ''"
      @update="emits('update')"
    />

    <!-- 改派部门弹窗 -->
    <update-network
      v-model="updateNetworkDialogVisible"
      :network="orderDetail.network || ''"
      :network-id="orderDetail.networkId"
      :order-id="orderDetail.id"
      :address="userAddress"
      @update="emits('update')"
    />

    <reservation-time
      v-model="reservationTimeDialogVisible"
      :work-id="orderDetail.id"
      @update="emits('update')"
    />

    <!-- 完成工单弹窗 -->
    <finish-order
      v-model="finishOrderDialogVisible"
      :order-ids="[orderDetail.id]"
      :is-batch="false"
      @update="emits('update')"
    />

    <!-- 取消工单弹窗 -->
    <cancel-order
      v-model="cancelDialogVisible"
      :is-batch="false"
      :order-ids="[orderDetail.id]"
      @update="emits('update')"
    />

    <!-- 催单弹窗 -->
    <reminder
      v-model="reminderDialogVisible"
      :order-ids="[orderDetail.id]"
      @update="emits('update')"
    />

    <!-- 更新工单信息弹窗 -->
    <update-order-info-modal
      v-model:visible="updateOrderInfoModalVisible"
      :order-id="orderDetail.id"
      @update="emits('update')"
    />

    <!-- 审核结单弹窗 -->
    <check-end-order-modal
      v-model="checkEndOrderModalVisible"
      :word-no="orderDetail.orderNo"
      :word-id="orderDetail.id"
      @update="emits('end-order-finish')"
    />

    <!-- 审核报价 -->
    <check-quote
      v-model="checkQuoteModalVisible"
      :order-id="props.orderDetail.id"
      @update="emits('check-quote-finish')"
    />

    <!-- 打印 -->
    <div>
      <div style="display: none">
        <order-print id="printId" ref="orderPrintInstance" :print-info="printInfo" />
      </div>
    </div>

    <assign-engineer-modal
      v-model="assignEngineerModalVisible"
      :order-detail="props.orderDetail"
      @update="emits('update')"
    />
  </div>
</template>

<style scoped lang="scss">
  .order_detail_header_btns {
    display: flex;
    gap: 5px;
  }
</style>
